﻿$(function() {
//Declare variable
	var  GroupName= $( "#GroupName" ),
		Discount = $( "#Discount" ),
		allFields = $( [] ).add( GroupName )
							.add(Discount),
		tips = $( ".validateTips" ),
		button_name="",
		url="a_usergroup.php", 
		ID="",
		AddTitle="Create new User Group",	
		EditTitle="Update User Group",	
		ViewTitle="View User Group",
		rowSelect="";
		rowNo=0;
		showLoader();
		
		$("#Discount").numeric();
		//Load First page
		LoadData(1,true);	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan='8' class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};	
		
		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );

		}
		
		function checkInputLimit(o,n,min){
			if ( parseFloat(o.val()) > min ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		
		function checkInputFile( o, n, min ) {
			if (o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Please input " + n + "." );
				return false;
			} else {
				return true;
			}
		}
		
		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
					
		function getData(id){
			var dataSet={'id':id,'m':'detail'};  
			 $.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
				
					//alert(data);
					
					var obj=eval('('+data+')');
					var header=eval("("+obj['header']+")");
					//set data to table
					GroupName.val(header['GroupName']);
					Discount.val(header['Discount']);
					if (header['Type']=="1"){
						$("#Type_1").attr('checked','checked');
						$("#Type_2").removeAttr('checked');
					}else{
						$("#Type_2").attr('checked','checked');
						$("#Type_1").removeAttr('checked');
					}
					
					$( "#PermissionTable tbody" ).append(obj['data']);
					//set row 
					$("#iCount").attr('innerHTML',obj['rows']);
				
				}
			});
		}
		
		function callAjax(obj,id){
			var m=$("#mode").val();
			
			rowNo=$("#rowCount").attr('innerHTML');
			if (m=="edit"){
				rowNo = rowSelect.find("td").eq(0).html();
			}
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":m,"var":obj,"id":id,"rows":rowNo},
				success: function(data){
					//alert(data);
					if (m=='add'){
					//	alert(data);
						//Insert data to first row.
						$( "#resultData tbody:first" ).prepend( data ); 
						//Set font color
						$( "#resultData tbody tr:first" ).css('color','blue');
						
						//Plus row number ;
						var rows=$("#rowCount").attr('innerHTML');
						$("#rowCount").attr('innerHTML',parseInt(rows,10)+1);
						
					}else if (m=='edit'){
						rowSelect.html(data);
					}
					// else if (m=='del'){
					// alert(data);
					// }
				
				}
			});
		}
		
		
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		//Confirm Dialog
		$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:160,
			autoOpen: false,
			modal: true
		});
		
		//Form Edit Add 
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			resizable:false,
			height: 550,
			zIndex:9999,
			width: 600,
			modal: true,
			open: function() { 
					$( "#PermissionTable tbody tr" ).remove();
					allFields.val( "" );
			},
			close: function() {
				$("#Type_1").attr('checked','checked');
				allFields.attr("readonly","");
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});
		// Set value from control to array 
		function getValue(){
			var add="",
				edit="",
				del="",
				view="",
				id="",
				o={},
				arlist=[];

			$('#PermissionTable tbody tr').each(function() {

				add =isNaN($(this).find("input[name=add]:checked").val())?'0':'1';
				edit = isNaN($(this).find("input[name=edit]:checked").val())?'0':'1';   
				del = isNaN($(this).find("input[name=delete]:checked").val())?'0':'1';   
				view = isNaN($(this).find("input[name=view]:checked").val())?'0':'1';   
				id=$(this).find("td").eq(1).html();    
				
				arlist.push({'id': id ,'view':view, 'add':add ,'edit':edit,'del':del});
				 
			});
			
			o={'groupname':GroupName.val(),'type':$("input:radio[name='Type']:checked").val(),'discount':Discount.val(),'list':arlist};
			return o;
		}
		// Check input data in control
		function checkRequireControl(){
			var bValid=true;
			bValid = bValid && checkInputFile( GroupName, "group name",1);
			bValid = bValid && checkInputFile( Discount, "discount",1);
			bValid = bValid && checkInputLimit( Discount, " discount not over 100%",100);
			 
			return bValid;
		}
		
		//Add Button
		$( "#btnAdd" ).live('click',function() {
			//set mode
			$("#mode").val("add");
			//Load content
			LoadPermissionTable();
			
			$("#dialog-form").dialog({'title':AddTitle});
			$( "#dialog-form" ).dialog( "open" );
			$( "#dialog-form" ).dialog( "option","buttons",{
				"Create":function(){
					allFields.removeClass( "ui-state-error" );
					if ( checkRequireControl() ) {
						callAjax(getValue(),0); // call ajax function for add new data
						$( this ).dialog( "close" );
					}
				},
				"Cancel":function(){$( this ).dialog( "close" );}
			});
			
			return false;
			
		});
			
		$(".btnEdit").live('click',function() {
				$("#mode").val("edit");
				rowSelect=$(this).parent().parent();
				ID= rowSelect.find("td").eq(1).html();
				getData(ID);
				$("#dialog-form").dialog({'title':EditTitle});
				$("#dialog-form").dialog("open");
				$("#dialog-form").dialog( "option","buttons",{
					"Update":function(){
						var bValid = true;
						allFields.removeClass( "ui-state-error" );
						if ( checkRequireControl() ) {
							callAjax(getValue(),ID); // call ajax for update 
							$( this ).dialog( "close" );
						}
					}
					,"Cancel":function(){
						$( this ).dialog( "close" );
					}
				}
				);
			});
		$(".btnDel").live('click',function(){
			var tableRow="";
			var irow=0;
				rowSelect = $(this).parent().parent();
				tableRow  = $(this).parent().parent().parent();
				ID=$(this).parent().parent().find("td").eq(1).html();
				irow=$(this).parent().parent().find("td").eq(0).html();
				
				//alert(ID);
				$("#mode").val("del");
				$("#dialog-confirm").dialog("open");
				$("#dialog-confirm").dialog("option","buttons",	{
					"Delete": function() {
						callAjax({"id":ID},0); 	//Call Ajax delete data
						rowSelect.remove(); // remove row
				
						tableRow.find("tr").each(function(){
							if (irow < parseInt($(this).find("td").eq(0).html()))
								$(this).find("td").eq(0).html( parseInt($(this).find("td").eq(0).html()) - 1 );	
						});
						//Remove number
						var rows=$("#rowCount").attr('innerHTML');
						$("#rowCount").attr('innerHTML',parseInt(rows,10)-1);
						
						$( this ).dialog( "close" );
					},
					Cancel: function() {
							$( this ).dialog( "close" );
					}
				});
			});
		$(".btnView").live('click', function(){
			$("#mode").val("view");
			ID=$(this).parent().parent().find("td").eq(1).html();
			getData(ID); // get detail data 
			allFields.val( "" ).removeClass( "ui-state-error" ),
			$( ".validateTips" ).html(''),
			$("#dialog-form").dialog({'title':ViewTitle}),
			$("#dialog-form").dialog("open"),
			$("#dialog-form").dialog("option","buttons",{
				"Close":function(){
					allFields.attr("readonly","");
					$( this ).dialog( "close" );
					}
				});
		});
		
		$("#btnSearch").click(function(){
			LoadData(1,true);
		});
		//Table mouse hover
		 $( "#PermissionTable tbody tr" ).live('hover',function(){
			$(this).toggleClass('authen-row-highlight');
		});
		
		function LoadPermissionTable(){
			var checkVal = $("input[name:Type]:checked").val();
			$( "#PermissionTable tbody tr" ).remove();
				 //Post 	
			$.post(url,  {'m':'authen','type':checkVal} , function(data){				 
					//convert string json to java json
					var obj=eval("(" + data + ")");
					//set data to table
					$( "#PermissionTable tbody" ).append(obj['data']);
					//set row 
					$("#iCount").attr('innerHTML',obj['rows']);
					//set page		
			});
 		}
		//check radio button
		$("input:radio[name=Type]").click(function(){
			// 0: Head Office , 1:Branch
			var chk_type=$("input:radio[name='Type']:checked").val();
			//Clear data
			 
			$( "#PermissionTable tbody tr" ).remove();
			//Post 	
			$.post(url,  {'m':'authen','type':chk_type} , function(data){				 
					//convert string json to java json
					var obj=eval("(" + data + ")");
					//set data to table
					$( "#PermissionTable tbody" ).append(obj['data']);
					//set row 
					$("#iCount").attr('innerHTML',obj['rows']);
					//set page		
			});		
		});
		
		function LoadData(page,b){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			var dataSet={'m':'search'
							,'name':$("#txtGroupName").val()	
							,'type':$("#cboType").val()
							,'page':page
							};
					
			 //Post 		
			 $.post(url,  dataSet , function(data){
				//alert(data);
				//hide loading
				hideLoader();
				//convert string json to java json
				var obj=eval("(" + data + ")");
				 
				//set data to table
				$( "#resultData tbody" ).append(obj['data']);
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				//set page
				if (b){

					if (parseInt(obj['totalpage'])>1){
						$("#paging_btn").show();
						setPaging(parseInt(obj['totalpage']));
					}else{
						$("#paging_btn").hide();
					}					
					 
				}
			 });
		}
 
			
		function setPaging(iTotal){
					 $("#paging_btn").paginate({
					count 		: iTotal,
					start 		: 1,
					display     : 10,
					border					: false,
					text_color  			: '#888',
					background_color    	: '#EEE',	
					text_hover_color  		: 'blue',
					background_hover_color	: '#CFCFCF',
					mouse					: 'press',
					onChange     			: function(page){
												LoadData(page,false);
											  }
				});
			}		
		
});
	